package com.inspur.edp.rule.dsl.core.function.list.getter;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.inspur.edp.rule.dsl.core.function.list.IGetFieldValue;

public class JsonGetter implements IGetFieldValue {

    private String fieldCode;

    public JsonGetter(String fieldCode) {
        this.fieldCode = fieldCode;
    }

    @Override
    public Object getFieldValue(Object object) {
        if (object == null) {
            return null;
        }
        return ((JsonNode) object).get(this.fieldCode);
    }

    @Override
    public String getString(Object object) {
        if (object instanceof NullNode) {
            return null;
        } else {
            Object fieldValue = getFieldValue(object);
            if (fieldValue instanceof NullNode) {
                return null;
            }
            return ((JsonNode) fieldValue).asText();
        }
    }

    @Override
    public Number getNumber(Object object) {
        JsonNode node = (JsonNode) getFieldValue(object);
        return node == null ? null : node.asDouble();
    }
}
